# 设置环境变量,查找项目python文件
import sys, os, math

curPath = os.path.abspath(os.path.dirname(__file__))
rootPath = os.path.split(curPath)[0]
sys.path.append(rootPath)

from flask import Flask, make_response, request
from tools import *
from tools.tool import result
from strategy import *
import json

app = Flask(__name__, static_folder='static')


@app.route("/")
def hello_world():
    return "<script>window.location = '/static/trade.html?code=SZ.000005';</script>"


@app.route('/data')
def data():
    # dataTool.resultDict()
    kdata = dataTool.getKdata('000005.SZ', startDate='20100101', endDate='20181231')
    kdata = kdata.to_dict('records')
    # kdata = json.dumps(kdata)
    # kdata = data.to_json(orient="records")
    kdata2 = []
    for val in kdata:
        item = []
        item.append(val['trade_date'])
        item.append(val['open'])
        item.append(val['close'])
        item.append(val['low'])
        item.append(val['high'])
        item.append(val['vol'])
        kdata2.append(item)

    # signals = dataTool.getSignals('000005.SZ', 'DoubleMaStg')
    # signals2 = signals['{"DoubleMaStg": {"fastPeriod": 10, "slowPeriod": 20}}']['detail']
    # signals = dataTool.getSignals('000005.SZ','{"MACDStg": {"fastPeriod": 12, "slowPeriod": 26, "signalPeriod": 9, "buy": "belowUp", "sell": "overDownX2"}}')
    signals = dataTool.getSignals('000005.SZ', '{"BollStg": {"timeperiod": 20, "type": "trend", "nbdev": 2}}')
    signals2 = signals['detail']
    signals2 = json.loads(signals2)
    for key, val in signals2.items():
        # signals2[key] = "+" if val[0] + val[1] > 0 else "-"
        signals2[key] = val[0] + val[1]
    res = {'data': kdata2, 'trade': signals2}
    return result(res)
    # return kdata


@app.route('/indicator')
def indicator():
    code = request.values.get('code')
    stg = request.values.get('stg')
    data = dataTool.getKdata(code, startDate='20100101', endDate='20181231')
    if stg == 'BollStg':
        upperband, middleband, lowerband = BollStg(data).initial()
        upperband2 = []
        middleband2 = []
        lowerband2 = []
        for val in upperband:
            upperband2.append(0 if math.isnan(val) else round(val, 3))
        for val in middleband:
            middleband2.append(0 if math.isnan(val) else round(val, 3))
        for val in lowerband:
            lowerband2.append(0 if math.isnan(val) else round(val, 3))
        res = {'upperband': upperband2, 'middleband': middleband2, 'lowerband': lowerband2}
        return result(res)


if __name__ == '__main__':
    app.run("localhost", 5000, True)
